package com.second.app.thread.线程基础.day01;

/**
 * @Author GYZ
 * @Date 2023/11/16
 * <pre>
 *
 *    案例1: 创建3个线程每个线程都要各自的count变量，自己减少自己的count变量的值。这样的情况就是变量不共享。
 *
 *    案例2: 多个线程共享同一个变量，导致线程安全。（多个线程，持有同一个线程实例对象）
 *
 *    案例3: 解决线程变量安全问题  run方法加上synchronized关键字，多个线程在执行run时，需要进行排队
 *          如果有其他线程正在执行run方法，需要等待调用结束后，当前线程才可以执行。
 * </pre>
 */
public class VariableModify {

    public static void main(String[] args) {

        //案例1
        class HisThread extends Thread {
            public HisThread(String threadName) {
                super(threadName);
            }

            int count = 5;

            @Override
            public void run() {
                while (count > 0) {
                    count--;
                    System.out.println(Thread.currentThread().getName() + "计算，count值：" + count);
                }
            }
        }
//        HisThread[] hisThreads = new HisThread[3];
//        hisThreads[0] = new HisThread("线程A");
//        hisThreads[1] = new HisThread("线程B");
//        hisThreads[2] = new HisThread("线程C");
//        for (HisThread hisThread : hisThreads) {
//            hisThread.start();
//        }

        //案例2
        class HerThread extends Thread {
            private int count = 5;

            @Override
            public synchronized void run() {
                count--;
                System.out.println(Thread.currentThread().getName() + "计算，count值：" + count);
            }
        }
        HerThread herThread = new HerThread();

        Runnable runnable = new Runnable() {
            private int count = 5;

            @Override
            public void run() {
                count--;
                System.out.println(Thread.currentThread().getName() + "计算，count值：" + count);
            }
        };
        //方式1
//        new Thread(runnable,"AA").start();
//        new Thread(runnable,"BB").start();
//        new Thread(runnable,"CC").start();
//        new Thread(runnable,"DD").start();
//        new Thread(runnable,"EE").start();

        //方式2
        new Thread(herThread, "AA").start();
        new Thread(herThread, "BB").start();
        new Thread(herThread, "CC").start();
        new Thread(herThread, "DD").start();
        new Thread(herThread, "EE").start();

    }
}
